<script>
import { cloneDeep, findIndex, flattenDeep, uniqBy } from 'lodash'
import {
  computed,
  defineComponent,
  onUnmounted,
  reactive,
  ref,
  toRaw,
  watch,
} from 'vue'
import * as Antd from 'ant-design-vue'
import ProductAttribute from '@Page/my/components/tag/productAttribute'
import { libFileDetail, libPicBatchAddTag } from '@Config/server/api'
import { tagListTagGroup } from '@Config/server/api'
import CheckBoxTags from '@Components/checkBoxTags'
import { message } from 'ant-design-vue'
import { Messages } from '@Config/config'
import Comment from '@Page/my/components/comment'

export default defineComponent({
  props: {
    allList: {
      type: Array, //当前目录下面，所有的图片
      default: () => {
        return []
      },
    },
    selected: {
      //当前选中的文件
      type: Array,
      default: () => {
        return []
      },
    },
    isComment: {
      type: Boolean,
      default: false,
    },
    isTag: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['result'],
  setup(props, context) {
    let pindex = ref(0)
    let loading = ref(false)
    //把当前选中的放到数组中来，并保持在第一的位置
    let allList = reactive({
      data: [],
    })

    if (props.selected.length == 1) {
      allList.data = [...props.allList]
      let _index = findIndex(allList.data, { id: props.selected[0].id })
      pindex.value = _index
    }

    let nextHandler = () => {
      tagsGroupList.selected = []
      pindex.value = pindex.value + 1
    }
    let preHandler = () => {
      tagsGroupList.selected = []

      pindex.value = pindex.value - 1
    }

    //获取产品详情
    let fullFile = reactive({})
    let marks = reactive({ data: [] })
    let _w = watch(
      () => pindex.value,
      async () => {
        let _id = allList.data[pindex.value].id
        loading.value = true
        let _r = await libFileDetail({
          id: _id,
          isTag: props.isTag ? 1 : 0,
          isComment: props.isComment ? 1 : 0,
          size: 5,
          index: 1,
        })
        loading.value = false
        for (var prop in _r.data) {
          fullFile[prop] = _r.data[prop]
        }
        marks.data = flattenDeep(
          _r.data.tagFileList?.map((x) => {
            return x.child
          })
        )
      },
      {
        immediate: true,
      }
    )
    onUnmounted(() => {
      _w()
    })

    let currentObject = computed(() => {
      return allList.data[pindex.value]
    })

    let tagsGroupList = reactive({ data: [], selected: [] })
    //加载个人标签组，以供用户快速选择标签集合
    tagListTagGroup({ size: 10000, index: 1 }).then((x) => {
      tagsGroupList.data = x.data.records.map((x) => {
        x.label = x.name
        x.value = x.id

        return x
      })
    })
    //标签分组
    let selectChangeHandler = async (e, option) => {
      // option.child.map((z) => {
      //   console.log(z)

      checkTagsRef.value.tags.data.map((x) => {
        option.child.map((z) => {
          let _index = findIndex(x.child, { id: z.tagId })
          if (_index >= 0) {
            x.child[_index].loading = true
          }
        })
      })

      let _r = await libPicBatchAddTag({
        ids: [currentObject.value.id],
        tagIdList: option.child.map((x) => x.tagId),
        model: 1,
      })

      checkTagsRef.value.tags.data.map((x) => {
        option.child.map((z) => {
          let _index = findIndex(x.child, { id: z.tagId })
          if (_index >= 0) {
            x.child[_index].loading = false
          }
        })
      })

      if (_r.code == 0) {
        Messages.add(message.success(`操作成功`))
        marks.data = flattenDeep(
          _r.data.map((x) => {
            return x.child.map((xx) => {
              return xx
            })
          })
        )
      }
    }

    //标签分组删除
    let dSelectHandler = async (value, option) => {
      checkTagsRef.value.tags.data.map((x) => {
        option.child.map((z) => {
          let _index = findIndex(x.child, { id: z.tagId })
          if (_index >= 0) {
            x.child[_index].loading = true
          }
        })
      })
      let _r = await libPicBatchAddTag({
        ids: [currentObject.value.id],
        tagIdList: option.child.map((x) => x.tagId),
        model: 0,
      })

      checkTagsRef.value.tags.data.map((x) => {
        option.child.map((z) => {
          let _index = findIndex(x.child, { id: z.tagId })
          if (_index >= 0) {
            x.child[_index].loading = false
          }
        })
      })
      if (_r.code == 0) {
        Messages.add(message.success(`操作成功`))
        option.child.map((x) => {
          let _index = findIndex(marks.data, { tagId: x.tagId })
          if (_index >= 0) {
            marks.data.splice(_index, 1)
          }
        })
      }
    }

    let checkboxSelectHandler = async ({ cate, tag, model }) => {
      let _r = await libPicBatchAddTag({
        ids: [currentObject.value.id],
        tagIdList: tag.map((x) => x.id),
        model: model,
      })
      tag.map((x) => {
        x.loading = false //shim
      })
      if (_r.code == 0 && model == 1) {
        Messages.add(message.success(`操作成功`))
        marks.data = flattenDeep(
          _r.data.map((x) => {
            return x.child.map((xx) => {
              return xx
            })
          })
        )
      } else if (_r.code == 0 && model == 0) {
        tag.map((x) => {
          let _index = findIndex(marks.data, { tagId: x.id })
          if (_index >= 0) {
            marks.data.splice(_index, 1)
          }
        })
      } else {
        Messages.add(message.error(`操作失败[${_r.msg}]`))
      }
    }
    /**
     * @description评论后，返回最新的数据，并更新界面
     * @param newRecord 新的数据
     * @param originId 更新数据的ID
     *
     */
    let commentResultHandler = ({ newRecord, originId }) => {
      let _temp = { ...toRaw(fullFile), ...newRecord }
      for (var prop in _temp) {
        fullFile[prop] = _temp[prop]
      }
    }

    let checkTagsRef = ref()
    return {
      checkTagsRef,
      allList,
      pindex,
      nextHandler,
      preHandler,
      fullFile,
      marks,
      loading,
      tagsGroupList,
      selectChangeHandler,
      dSelectHandler,
      checkboxSelectHandler,
      props,
      currentObject,
      commentResultHandler,
    }
  },
  render() {
    return this.loading ? (
      <Antd.Spin tip="加载数据中..." />
    ) : (
      <Antd.Row gutter={[20, 20]}>
        <Antd.Col span={24}>
          <ProductAttribute product={{ ...this.fullFile }} />
        </Antd.Col>
        <Antd.Col span={24}>
          <Antd.Space>
            <Antd.Button
              onClick={this.preHandler}
              disabled={this.pindex == 0 || this.loading == true}
            >
              上一张
            </Antd.Button>
            <Antd.Button
              onClick={this.nextHandler}
              disabled={
                this.pindex == this.allList.data.length - 1 ||
                this.loading == true
              }
            >
              下一张
            </Antd.Button>
            {this.isTag && (
              <Antd.Select
                style={{ 'min-width': '200px' }}
                options={this.tagsGroupList.data}
                placeholder="标签组选项"
                value={this.tagsGroupList.selected}
                mode="multiple"
                onSelect={this.selectChangeHandler}
                onDeselect={this.dSelectHandler}
              ></Antd.Select>
            )}
          </Antd.Space>
        </Antd.Col>
        <Antd.Col span={24}>
          {this.props.isTag && (
            <CheckBoxTags
              onSelect={this.checkboxSelectHandler}
              selectedList={this.marks.data}
              ref="checkTagsRef"
            />
          )}
          {this.props.isComment && (
            <Comment
              comment={this.fullFile.comment}
              file={this.currentObject}
              onResult={this.commentResultHandler}
            />
          )}
        </Antd.Col>
      </Antd.Row>
    )
  },
})
</script>
